package com.zhoug.zmui;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;

import com.zhoug.common.utils.LogUtils;

/**
 * 两端分散对齐TextView 有英文字母和特殊字符时可能导致显示不全的bug
 * 1. android:ems  所有的组件设置成最多的文字的那个组件的文字的数目,即会分散对齐
 *例子:
 *   <com.zhoug.zmui.ZMUIAlignTextView
 *                     android:layout_width="wrap_content"
 *                     android:layout_height="wrap_content"
 *                     android:ems="8"
 *                     app:zmui_prefix="*"
 *                     app:zmui_prefixColor="#ff0000"
 *                     app:zmui_prefixVisibility="visible"
 *                     app:zmui_suffix=":"
 *                     app:zmui_suffixVisibility="visible"
 *                     app:zmui_text="统一社会信用代码" />
 * @Author 35574
 * @Date 2020/11/9
 * @Description
 * @see ZMUIAlignmentTextView
 */
public class ZMUIAlignTextView extends androidx.appcompat.widget.AppCompatTextView {
    private static final String TAG = ">>>ZMUIAlignTextView";
    private static  boolean debug = false;

    /***
     * 文本
     */
    private String text;
    /**
     * 前缀
     */
    private String prefix;
    /**
     * 后缀
     */
    private String suffix;
    /**
     * 前缀颜色:设置0则使用文本颜色
     */
    private int prefixColor;
    /**
     * 后缀颜色:设置0则使用文本颜色
     */
    private int suffixColor;
    /**
     * 前缀显示模式
     */
    private Visibility prefixVisibility;
    /**
     * 后缀显示模式
     */
    private Visibility suffixVisibility;


    public enum Visibility {
        VISIBLE, INVISIBLE, GONE,
    }

    public static void setDebug(boolean debug) {
        ZMUIAlignTextView.debug = debug;
    }

    public ZMUIAlignTextView(Context context) {
        this(context, null);

    }

    public ZMUIAlignTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ZMUIAlignTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ZMUIAlignTextView, defStyleAttr, R.style.ZMUIAlignTextView);
        text = typedArray.getString(R.styleable.ZMUIAlignTextView_zmui_text);
        prefix = typedArray.getString(R.styleable.ZMUIAlignTextView_zmui_prefix);
        suffix = typedArray.getString(R.styleable.ZMUIAlignTextView_zmui_suffix);
        prefixColor = typedArray.getColor(R.styleable.ZMUIAlignTextView_zmui_prefixColor, 0);
        suffixColor = typedArray.getColor(R.styleable.ZMUIAlignTextView_zmui_suffixColor, 0);
        int _prefixVisibility = typedArray.getInt(R.styleable.ZMUIAlignTextView_zmui_prefixVisibility, 0);
        int _suffixVisibility = typedArray.getColor(R.styleable.ZMUIAlignTextView_zmui_suffixVisibility, 0);
        switch (_prefixVisibility) {
            case 1:
                prefixVisibility = Visibility.INVISIBLE;
                break;
            case 2:
                prefixVisibility = Visibility.GONE;
                break;
            default:
                prefixVisibility = Visibility.VISIBLE;
        }
        switch (_suffixVisibility) {
            case 1:
                suffixVisibility = Visibility.INVISIBLE;
                break;
            case 2:
                suffixVisibility = Visibility.GONE;
                break;
            default:
                suffixVisibility = Visibility.VISIBLE;
        }
        typedArray.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        TextPaint paint = getPaint();
        paint.setTextSize(getTextSize());
        //测量宽度
        if (widthMode != MeasureSpec.EXACTLY) {
            //文本需要的宽度
            float width =getStringWidth(paint, text);
            int maxEms = getMaxEms();
            if (debug) {
                LogUtils.d(TAG, "onMeasure:maxEms=" + maxEms);
            }
            if (maxEms != -1) {
                width = Math.min(width, maxEms * getTextSize());
            }
            int minEms = getMinEms();
            if (debug) {
                LogUtils.d(TAG, "onMeasure:minEms=" + minEms);
            }
            if (minEms != -1) {
                width = Math.max(width, minEms * getTextSize());
            }
            //加上前后缀的宽度
            width+= getStringWidth(paint, prefix) + getStringWidth(paint, suffix);
            if(widthSize>0){
                width=Math.min(width,widthSize);
            }
            super.onMeasure(MeasureSpec.makeMeasureSpec((int) (width+0.5f),MeasureSpec.EXACTLY), heightMeasureSpec);
        }else{
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }


    @Override
    protected void onDraw(Canvas canvas) {
        TextPaint paint = getPaint();
        paint.setTextSize(getTextSize());
        if (debug) {
            LogUtils.d(TAG, "onDraw:getMeasuredWidth=" + getMeasuredWidth());
        }
        if (TextUtils.isEmpty(text) && TextUtils.isEmpty(prefix) && TextUtils.isEmpty(suffix)) {
            super.onDraw(canvas);
            return;
        }
        //测量基准线
        Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
        int baseline = (getMeasuredHeight() - fontMetrics.bottom - fontMetrics.top) / 2;
        //前缀宽度
        float prefixWidth = getStringWidth(paint, prefix);
        //后缀宽度
        float suffixWidth = getStringWidth(paint, suffix);
        if (debug) {
            LogUtils.d(TAG, "onDraw:prefixWidth=" + prefixWidth + ",suffixWidth=" + suffixWidth);
        }
        //画前缀
        int x = getPaddingStart();

        if (!TextUtils.isEmpty(prefix)) {
            if (debug) {
                LogUtils.d(TAG, "onDraw:画前缀 x=" + x);
            }
            if (prefixVisibility == Visibility.VISIBLE) {
                paint.setColor(prefixColor != 0 ? prefixColor : getTextColors().getDefaultColor());
                canvas.drawText(prefix, x, baseline, paint);
                x += prefixWidth;
            } else if (prefixVisibility == Visibility.INVISIBLE) {
                x += prefixWidth;
            }
        }
        //画文本
        char[] chars = text.toCharArray();
        if (chars != null && chars.length > 0) {
            paint.setColor(getTextColors().getDefaultColor());
            //每个文字的大小
            float textPx = getTextSize();
            //文本总宽度
            int maxTextViewWidth = getMeasuredWidth() - getPaddingStart() - getPaddingEnd();
            if (prefixVisibility != Visibility.GONE) {
                //减去前缀宽度
                maxTextViewWidth -= prefixWidth;
            }
            if (suffixVisibility != Visibility.GONE) {
                //减去后缀宽度
                maxTextViewWidth -= suffixWidth;
            }
            if (debug) {
                LogUtils.d(TAG, "onDraw:maxTextViewWidth=" + maxTextViewWidth);
            }
            //文本间距
            int spec = (int) ((maxTextViewWidth - chars.length * textPx) / (chars.length - 1));
            if(spec<0){
                spec=0;
            }
            if (debug) {
                LogUtils.d(TAG, "onDraw:spec=" + spec);
            }
            for (int i = 0; i < chars.length; i++) {
                canvas.drawText(String.valueOf(chars[i]), x, baseline, paint);
                if (i != chars.length - 1) {
                    x += textPx + spec;
                } else {
                    x += textPx;
                }
            }
        }
        //画后缀
        if (!TextUtils.isEmpty(suffix)) {
            if (suffixVisibility == Visibility.VISIBLE) {
                paint.setColor(suffixColor != 0 ? suffixColor : getTextColors().getDefaultColor());
                canvas.drawText(suffix, x, baseline, paint);
            }
        }


    }

    /**
     * 计算文本的宽度
     * @param paint
     * @param str
     * @return
     */
    private float getStringWidth(Paint paint, String str) {
        if (TextUtils.isEmpty(str)) {
            return 0;
        }
        return paint.measureText(str);
    }

    public void setText(String text) {
        this.text = text;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }

    public void setPrefixColor(int prefixColor) {
        this.prefixColor = prefixColor;
    }

    public void setSuffixColor(int suffixColor) {
        this.suffixColor = suffixColor;
    }

    public void setPrefixVisibility(Visibility prefixVisibility) {
        this.prefixVisibility = prefixVisibility;
    }

    public void setSuffixVisibility(Visibility suffixVisibility) {
        this.suffixVisibility = suffixVisibility;
    }

}
